package cn.bonoon.services.plugins;

import java.util.Date;
import java.util.List;

import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.plugins.MessageAcceptService;
import cn.bonoon.entities.interacting.MessageAcceptEntity;
import cn.bonoon.entities.interacting.MessageEntity;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.support.services.AbstractSearchService;

@Service
@Transactional(readOnly = true)
public class MessageAcceptServiceImpl extends AbstractSearchService<MessageAcceptEntity> implements MessageAcceptService {

	@Override
	@Transactional
	public MessageEntity read(Long id) {
		MessageAcceptEntity mae = get(id);
		if (!mae.isHasRead()) {
			mae.setHasRead(true);
			mae.setReadAt(new Date());
			entityManager.merge(mae);
		}
		return mae.getMessage();
	}

	// @Override
	// public Page_delete<MessageAcceptEntity> myMessages(PageCondition
	// condition, Long id) {
	// String ql =
	// "from MessageAcceptEntity x where x.accepterId=?1 and hasRead=false";
	// return __page(MessageAcceptEntity.class, ql, condition, id);
	// }

	@Override
	public int unreadCount(Long id) {
		String ql = "select count(x) from MessageAcceptEntity x where x.accepterId=? and hasRead=false";
		return __single(Number.class, ql, id).intValue();
	}

	@Override
	@Transactional
	public List<MessageAcceptEntity> getNewMessage(IOperator opt) {
		String ql = "from MessageAcceptEntity x where x.accepterId=? and x.hasRead=false order by x.message.createAt desc";
		List<MessageAcceptEntity> messageAccept = __list(MessageAcceptEntity.class, ql, opt.getId());
		for (MessageAcceptEntity entity : messageAccept) {
			entity.setHasRead(true);
			entity.setReadAt(new Date());
			entityManager.merge(entity);
		}
		return messageAccept;
	}

	@Override
	public List<MessageAcceptEntity> getSysMessage(IOperator opt, Long page) {
		String ql = "from MessageAcceptEntity x where x.message.status=0 and x.accepterId=? order by x.message.createAt desc";
		TypedQuery<MessageAcceptEntity> tqSelect = __query(MessageAcceptEntity.class, ql, opt.getId());
		tqSelect.setFirstResult((int) ((page - 1) * 10));
		tqSelect.setMaxResults(10);
		return tqSelect.getResultList();
	}

	@Override
	public List<MessageAcceptEntity> getPerMessage(IOperator opt, Long page) {
		String ql = "from MessageAcceptEntity x where x.message.status=1 and x.accepterId=? order by x.message.createAt desc";
		TypedQuery<MessageAcceptEntity> tqSelect = __query(MessageAcceptEntity.class, ql, opt.getId());
		tqSelect.setFirstResult((int) ((page - 1) * 10));
		tqSelect.setMaxResults(10);
		return tqSelect.getResultList();
	}

}
